package io.kiki.sba.registry.server.metadata.resource;

import com.fasterxml.jackson.core.type.TypeReference;
import io.kiki.sba.registry.common.model.CollectionSdks;
import io.kiki.sba.registry.common.model.GenericResponse;
import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress.AddressVersion;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerResult;
import io.kiki.sba.registry.server.shared.client.manager.ClientManagerService;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.OperationStatus;
import io.kiki.sba.registry.util.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Set;

/**
 * The type Clients open resource.
 */
@Path("api/clientManager")
@Produces(MediaType.APPLICATION_JSON)
public class ClientManagerResource {

    public static final TypeReference<Set<AddressVersion>> FORMAT = new TypeReference<Set<AddressVersion>>() {
    };
    private static final Logger logger = LoggerFactory.getLogger(ClientManagerResource.class);
    @Resource
    private ClientManagerService clientManagerService;

    /**
     * Client off
     *
     * @param ips ips
     * @return CommonResponse
     */
    @POST
    @Path("/clientOff")
    public Response clientOff(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return Response.buildFailedResponse("ips is empty");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.clientOff(ipSet);

        logger.info("client off result:{}, ips:{}", ret, ips);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret.isSuccess());
        return response;
    }

    /**
     * Client off
     *
     * @param ips
     * @return CommonResponse
     */
    @POST
    @Path("/clientOffWithSub")
    public Response clientOffWithSub(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return Response.buildFailedResponse("ips is empty");
        }

        Set<AddressVersion> read = JsonUtils.read(ips, FORMAT);
        if (!validate(read)) {
            logger.error("client off new error, ips:{}", read);
            return Response.buildFailedResponse("ips is invalidate");
        }

        ClientManagerResult ret = clientManagerService.clientOffWithSub(read);

        logger.info("client off result:{}, ips:{}", ret, ips);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret.isSuccess());
        return response;
    }

    private boolean validate(Set<AddressVersion> list) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        for (AddressVersion address : list) {
            if (!address.isPub() && !address.isSub()) {
                return false;
            }
        }
        return true;
    }

    /**
     * Client Open
     *
     * @param ips
     * @return CommonResponse
     */
    @POST
    @Path("/clientOpen")
    public Response clientOpen(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return Response.buildFailedResponse("ips is empty");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.clientOpen(ipSet);

        logger.info("client open result:{}, ips:{}", ret, ips);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret.isSuccess());
        return response;
    }

    /**
     * Client Open
     *
     * @param ips ips
     * @return CommonResponse
     */
    @POST
    @Path("/reduce")
    public Response reduce(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return Response.buildFailedResponse("ips is empty");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.reduce(ipSet);

        logger.info("reduce result:{}, ips:{}", ret, ips);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret.isSuccess());
        return response;
    }

    /**
     * Client Open
     *
     * @return GenericResponse
     */
    @GET
    @Path("/query")
    public GenericResponse<ClientManagerAddress> query() {
        DBResponse<ClientManagerAddress> ret = clientManagerService.queryClientOffAddress();
        logger.info("client off result:{}", ret.getOperationStatus(), ret.getEntity());

        if (ret.getOperationStatus() != OperationStatus.success) {
            return new GenericResponse<ClientManagerAddress>().fillFailed("data not found");
        }
        return new GenericResponse<ClientManagerAddress>().fillSucceed(ret.getEntity());
    }

    /**
     * Setter method for property <tt>clientManagerService</tt>.
     *
     * @param clientManagerService value to be assigned to property clientManagerService
     * @return ClientManagerResource
     */

    public ClientManagerResource setClientManagerService(ClientManagerService clientManagerService) {
        this.clientManagerService = clientManagerService;
        return this;
    }
}
